const config = require('./config.js');
const Base64 = require('./lib/base64.js');

require('./lib//hmac.js');
require('./lib/sha1.js');

const Crypto = require('./lib/crypto.js');

const uploadFile = function(parmas){
    let filePath = parmas.filePath;
    let dir = parmas.dir;
    // 获取文件后缀
    let pathArr = filePath.split('.');
    //  随机生成文件名称
    let fileRandName = Date.now() + "" + parseInt(Math.random() * 1000);
    let fileName = fileRandName + '.' + pathArr[pathArr.length - 1];
    // 要提交的key
    let fileKey = dir + '/' + fileName;
    let host = config.uploadImageUrl;

    let policyBase64 = Base64.encode(JSON.stringify(config.policyText));
    let message = policyBase64;
    let bytes = Crypto.HMAC(Crypto.SHA1, message, config.accesskey, { asBytes: true });
    let signature = Crypto.util.bytesToBase64(bytes);
    let accessKeyId = config.accessid;

    // console.log("==========>" + policyBase64);
    // console.log("---------->" + signature);

    // console.log("---------->" + host);
    if(!filePath){
        parmas.fail('filePath is not found');
        return;
    }
    wx.uploadFile({
        url: host,
        filePath: filePath,
        name: 'file',
        formData: {
            name: filePath,
            key: fileKey,
            policy: policyBase64,
            OSSAccessKeyId: accessKeyId,
            signature: signature,
            success_action_status: "200"
        },
        success: function (res) {
            if (res.statusCode != 200) {
                if (parmas.fail) {
                    parmas.fail(res)
                }
                return;
            }
            if (parmas.success) {
                res.imgUrl = host+"/"+fileKey;
                parmas.success(res);
            }
        },
        fail: function (err) {
            err.wxaddinfo = host;
            if (parmas.fail) {
                parmas.fail(err)
            }
        }
    });
}

module.exports = uploadFile;